package org.znxs.znmanus.controller;


import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.znxs.znmanus.agent.ZNManus;
import org.znxs.znmanus.agent.tools.UserInputQueue;
import org.znxs.znmanus.tools.QueryUserTool;

import java.util.Collections;
import java.util.Map;


@RestController
@RequestMapping("/ai")
@Slf4j
public class AIController {

    private static final String ZNMANUS_STATUS = "znManus_status";

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ChatModel dashscopeChatModel;

    /**
     * 左拿智能体
     *
     * @param query
     * @param request
     * @return
     */
    @GetMapping("/chat/ZnManus")
    public SseEmitter ZnManus(@RequestParam(value = "query") String query, HttpServletRequest request) {
        // 权限判断 将sk 作为id 判断每个用户


        ZNManus znManus = new ZNManus(allTools, dashscopeChatModel);
        SseEmitter sseEmitter = znManus.runStream(query);
        request.getSession().setAttribute(ZNMANUS_STATUS, znManus.getStatus());
        return sseEmitter;
    }


    @Resource
    private UserInputQueue userInputQueue;

    @Resource
    private QueryUserTool queryUserTool;

    /**
     * 询问用户后，用户输入接口后，前端进行调用该接口，把用户输入的内容传递到内容中
     *
     * @param input 用户输入内容
     * @return
     */
    @GetMapping("/user/input")
    public void userInput(@RequestParam("input") String input, HttpServletRequest request) {

        // 回答问题
        try {
            // 判断是否在询问用户中
            if (!queryUserTool.isUserQueried()) {
                log.warn("错误的输入时机，用户在没询问的时候输入");
                return;
            }
            // 非空判断
            if (StrUtil.isBlank(input)) {
                userInputQueue.putResponse("用户输入为空");
            } else {
                userInputQueue.putResponse(input);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    @Value("${spring.ai.dashscope.api-key}")
    private String apikey;

    @GetMapping("/config/check")
    public Map<String, String> checkConfig() {
        return Collections.singletonMap("apikey", apikey);
    }



}
